﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Threading.Tasks;
using CrawlerCore;
using WCrawlerLib;

namespace WCrawler
{
    public partial class frmHost : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                gridViewHost.DataBind();
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            Parallel.ForEach<GridViewRow>(gridViewHost.Rows.OfType<GridViewRow>(), di =>
            {
                CheckBox chkBx = (CheckBox)di.FindControl("chkCheckItem");
                if (chkBx != null && chkBx.Checked)
                {
                    Host objHost = new Host();
                    objHost.UpdateInformation((int)gridViewHost.DataKeys[di.RowIndex].Value);
                }
            });
            gridViewHost.DataBind();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Host objHost = new Host();
            string hostName = GeneralClass.GetName(txtHostUrl.Text);
            if (!objHost.IsExist(hostName))
            {
                objHost.AddHost(hostName, txtHostUrl.Text);
                lblMessage.Text = "Add Successful!";
            }
            else
            {
                lblMessage.Text = "The host is exist";
            }
            gridViewHost.DataBind();
        }

        protected void gridViewHost_SelectedIndexChanged(object sender, EventArgs e)
        {
            DetailsViewHost.DataBind();
        }

        protected void DetailViewHostLinqDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            if (gridViewHost.SelectedDataKey != null)
            {
                Host objHost = new Host();
                e.Result = objHost.GetHost((int)gridViewHost.SelectedDataKey["HostId"]);
            }
        }

        protected void DetailsViewHost_ItemDeleted(object sender, DetailsViewDeletedEventArgs e)
        {
            gridViewHost.DataBind();
        }

        protected void DetailsViewHost_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
        {
            gridViewHost.DataBind();
        }
    }
}